<template>
  <div class="player-page">
    <div class="player-container">
      <!-- 视频播放器 -->
      <div v-if="media?.type === 'video'" class="video-player">
        <video
          ref="videoRef"
          :src="media.url"
          :poster="media.thumbnail"
          controls
          preload="metadata"
          @loadedmetadata="handleLoadedMetadata"
          @timeupdate="handleTimeUpdate"
          @ended="handleEnded"
        >
          您的浏览器不支持视频播放
        </video>
      </div>

      <!-- 音频播放器 -->
      <div v-else-if="media?.type === 'audio'" class="audio-player">
        <div class="audio-cover">
          <el-icon size="120"><Headphone /></el-icon>
        </div>
        <audio
          ref="audioRef"
          :src="media.url"
          controls
          preload="metadata"
          @loadedmetadata="handleLoadedMetadata"
          @timeupdate="handleTimeUpdate"
          @ended="handleEnded"
        >
          您的浏览器不支持音频播放
        </audio>
      </div>

      <!-- 加载状态 -->
      <div v-else class="loading-state">
        <el-icon size="64"><Loading /></el-icon>
        <p>加载中...</p>
      </div>
    </div>

    <!-- 媒体信息 -->
    <div class="media-info-panel">
      <el-card v-if="media">
        <div class="media-header">
          <h2>{{ media.name }}</h2>
          <div class="media-actions">
            <el-button @click="toggleLike" :type="isLiked ? 'primary' : 'default'">
              <el-icon><Star /></el-icon>
              {{ media.likes + (isLiked ? 1 : 0) }}
            </el-button>
            <el-button @click="handleShare">
              <el-icon><Share /></el-icon>
              分享
            </el-button>
            <el-button @click="handleDownload">
              <el-icon><Download /></el-icon>
              下载
            </el-button>
          </div>
        </div>

        <div class="media-meta">
          <el-row :gutter="16">
            <el-col :span="8">
              <div class="meta-item">
                <span class="meta-label">分类：</span>
                <el-tag>{{ media.category }}</el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="meta-item">
                <span class="meta-label">格式：</span>
                <span>{{ media.format.toUpperCase() }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="meta-item">
                <span class="meta-label">大小：</span>
                <span>{{ formatFileSize(media.size) }}</span>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="16" style="margin-top: 12px;">
            <el-col :span="8">
              <div class="meta-item">
                <span class="meta-label">时长：</span>
                <span>{{ formatDuration(media.duration) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="meta-item">
                <span class="meta-label">播放量：</span>
                <span>{{ media.views + 1 }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="meta-item">
                <span class="meta-label">上传时间：</span>
                <span>{{ media.uploadTime }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div v-if="media.tags.length > 0" class="media-tags">
          <span class="meta-label">标签：</span>
          <el-tag
            v-for="tag in media.tags"
            :key="tag"
            style="margin-right: 8px;"
          >
            {{ tag }}
          </el-tag>
        </div>

        <div v-if="media.description" class="media-description">
          <h4>描述</h4>
          <p>{{ media.description }}</p>
        </div>
      </el-card>

      <!-- 相关推荐 -->
      <el-card style="margin-top: 16px;">
        <template #header>
          <span>相关推荐</span>
        </template>
        
        <div class="related-list">
          <div
            v-for="item in relatedMedia"
            :key="item.id"
            class="related-item"
            @click="playRelated(item)"
          >
            <div class="related-thumbnail">
              <el-image
                v-if="item.type === 'video' && item.thumbnail"
                :src="item.thumbnail"
                fit="cover"
              />
              <div v-else class="thumbnail-placeholder">
                <el-icon size="24">
                  <VideoCamera v-if="item.type === 'video'" />
                  <Headphone v-else />
                </el-icon>
              </div>
            </div>
            <div class="related-info">
              <div class="related-title">{{ item.name }}</div>
              <div class="related-meta">
                {{ item.views }} 次播放 · {{ formatDuration(item.duration) }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { mediaApi } from '@/api/modules/media'
import type { MediaFile } from '@/types'

const route = useRoute()
const router = useRouter()

const videoRef = ref<HTMLVideoElement>()
const audioRef = ref<HTMLAudioElement>()
const media = ref<MediaFile>()
const isLiked = ref(false)
const relatedMedia = ref<MediaFile[]>([])

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

// 加载媒体数据
const loadMedia = async (id: string) => {
  try {
    const result = await mediaApi.getMediaFile(id)
    media.value = result || undefined
    if (!media.value) {
      ElMessage.error('媒体文件不存在')
      router.push('/media-library')
      return
    }

    // 加载相关推荐
    const listResult = await mediaApi.getMediaFiles({ 
      page: 1, 
      pageSize: 5,
      category: media.value.category 
    })
    relatedMedia.value = listResult.list.filter(item => item.id !== id)
  } catch (error) {
    ElMessage.error('加载媒体文件失败')
  }
}

// 媒体加载完成
const handleLoadedMetadata = () => {
  console.log('媒体加载完成')
}

// 播放进度更新
const handleTimeUpdate = () => {
  // 可以在这里更新播放进度
}

// 播放结束
const handleEnded = () => {
  console.log('播放结束')
  // 可以自动播放下一个
}

// 切换点赞
const toggleLike = () => {
  isLiked.value = !isLiked.value
  ElMessage.success(isLiked.value ? '已点赞' : '已取消点赞')
}

// 分享
const handleShare = () => {
  if (navigator.share) {
    navigator.share({
      title: media.value?.name,
      url: window.location.href
    })
  } else {
    // 复制链接到剪贴板
    navigator.clipboard.writeText(window.location.href)
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 下载
const handleDownload = () => {
  if (media.value) {
    const link = document.createElement('a')
    link.href = media.value.url
    link.download = media.value.name
    link.click()
  }
}

// 播放相关媒体
const playRelated = (item: MediaFile) => {
  router.push(`/player/${item.id}`)
}

onMounted(() => {
  const id = route.params.id as string
  if (id) {
    loadMedia(id)
  }
})

// 监听路由变化
onUnmounted(() => {
  // 清理资源
  if (videoRef.value) {
    videoRef.value.pause()
  }
  if (audioRef.value) {
    audioRef.value.pause()
  }
})
</script>

<style scoped>
.player-page {
  display: flex;
  gap: 24px;
  padding: 0;
  height: calc(100vh - 140px);
}

.player-container {
  flex: 2;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  width: 100%;
  height: 100%;
}

.video-player video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.audio-player {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
  padding: 40px;
}

.audio-cover {
  margin-bottom: 24px;
}

.audio-player audio {
  width: 100%;
  max-width: 400px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.media-info-panel {
  flex: 1;
  max-height: 100%;
  overflow-y: auto;
}

.media-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.media-header h2 {
  margin: 0;
  flex: 1;
  margin-right: 16px;
}

.media-actions {
  display: flex;
  gap: 8px;
}

.media-meta {
  margin-bottom: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.meta-label {
  font-weight: 500;
  margin-right: 8px;
  min-width: 60px;
}

.media-tags {
  margin-bottom: 16px;
}

.media-description h4 {
  margin: 0 0 8px 0;
}

.media-description p {
  margin: 0;
  line-height: 1.6;
  color: #666;
}

.related-list {
  max-height: 400px;
  overflow-y: auto;
}

.related-item {
  display: flex;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.related-item:hover {
  background-color: #f5f5f5;
}

.related-thumbnail {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 12px;
  background: #f0f0f0;
}

.related-thumbnail .el-image {
  width: 100%;
  height: 100%;
}

.thumbnail-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
}

.related-info {
  flex: 1;
}

.related-title {
  font-weight: 500;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-meta {
  font-size: 12px;
  color: #666;
}
</style> 